module(..., package.seeall)

local imgPath = "images/"
local myImages2 = {
	"jessica_100.jpg",
	"andy_100.jpg",
	"aya_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg"
}
local myImages = {}
for row in db:nrows("SELECT * FROM coinbox") do
	--local text = row._id.." "..row._id
	--if (row.is_unlock == 1) then
	print("coin: ", row.coin_count)
	table.insert(myImages, row._id, imgPath..row.coin_img) 
	--token_count = row.coin_count
end

--popup grid
itemWidth = 50
itemHeight = 50
unit_w = 50
unit_h = 50
local gridGroup = display.newGroup()
function makeTiles(rowcnt,colcnt,unit_w,unit_h,cellpadding,leftmargin,topmargin)
	--gridbg
	local 	gridbg = display.newRect( 0, 0, colcnt*(unit_w+cellpadding)+leftmargin, rowcnt*(unit_h+cellpadding)+topmargin )
			gridbg:setFillColor(140, 140, 140)
			gridbg:setStrokeColor(180, 180, 180)
			gridGroup:insert(gridbg)
	
	for i = 1, rowcnt, 1 do
		for j = 1, colcnt, 1 do
			x = (j-1)*(unit_w + cellpadding)+leftmargin
			y = topmargin + (i-1)*(unit_h + cellpadding)
			local unit = display.newRect( x, y, unit_w, unit_h )
			--gridGroup:insert(unit)

		end
	end
end

function popMonster()
	print("popupmonster")
	--bb("Jasika")
end

function putGrid(row,column,img,grid,cellpadding,leftmargin,topmargin)
	local  item = display.newImageRect( img, itemWidth, itemHeight )
	item.x = (column-1)*(unit_w + cellpadding) + leftmargin+25
	item.y = topmargin + (row-1)*(unit_h + cellpadding) + 25
	item:addEventListener("tap", popMonster)
	grid:insert(item)
end


function cb(localGroup)
	local bdr = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
	bdr:setReferencePoint(display.BottomLeftReferencePoint) 
	bdr.strokeWidth = 1
	bdr:setFillColor(100, 100, 100)
	bdr:setStrokeColor(0, 222, 222)
	bdr.alpha = 0.5
	
	local fncProtection = function( event )
		return true
	end	
	bdr:addEventListener( "touch", fncProtection )

	local closeBtn = display.newImage("images/cross_32.png") 
	function closeBtn:tap(e)  
		--bdr.isVisible = false;
		print("pangkah!!!")
		bdr:removeSelf()
		fncProtection = nil
		closeBtn:removeSelf()
		--gridGroup:removeChildren(); 
		if gridGroup.numChildren > 0 then
				for i=gridGroup.numChildren,1,-1 do
				   gridGroup[i]:removeSelf()
				   gridGroup[i] = nil
				end
		end 
--			
	end  
	closeBtn:addEventListener( "tap", closeBtn )
	
	makeTiles(4,5,50,50,10,10,5)
	localGroup:insert(bdr)
	gridGroup:insert(closeBtn)
	localGroup:insert(gridGroup)
	gridGroup.x = 5
	gridGroup.y = 60
	closeBtn.x = 300
	closeBtn.y = -10
	--for i=1,#myImages,1 do
	for i=1,6,1 do
		maxrow=5
		maxcol=5
		r = math.ceil(i/maxrow) --what row?
		c = i - (r-1)*maxcol    --what column?
		putGrid(r,c,myImages[i],gridGroup,10,10,5)
		print("row=",r ,"col=", c)
	end
end
